<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import useCompute from '@renderer/composables/useCompute'
import useComputeForm from '@renderer/composables/useComputeForm'
import addCeiling from '@renderer/views/compute/components/addCeiling.vue'
import addOther from '@renderer/views/compute/components/addOther.vue'
import addRoom from '@renderer/views/compute/components/addRoom.vue'
import addTile from '@renderer/views/compute/components/addTile.vue'
import addWardrobe from '@renderer/views/compute/components/addWardrobe.vue'
import { Action, ElMessageBox } from 'element-plus'
import { ref, useTemplateRef, watch } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter()
const pageQuery = route.currentRoute.value.query
const props = defineProps<{
  menuName: string
}>()
watch(props, () => {
  if (['瓷砖数据', '户型数据', '木工数据', '柜子数据', '其他数据'].includes(props.menuName)) {
    let element = null as HTMLElement | null
    switch (props.menuName) {
      case '瓷砖数据':
        element = document.getElementById('tileRef')
        break
      case '户型数据':
        element = document.getElementById('roomRef')
        break
      case '木工数据':
        element = document.getElementById('ceilingRef')
        break
      case '柜子数据':
        element = document.getElementById('wardrobeRef')
        break
      case '其他数据':
        element = document.getElementById('otherRef')
        break
    }
    if (element) {
      element.scrollIntoView({ behavior: 'smooth' })
    }
  }
})
const tileRef = ref<{ colData }>()
const mineRoomRef = useTemplateRef('mineRoomRef')
const ceilingRef = ref<{ getceilingData: Function; getComputeHouseInfo: Function }>()
const wardrobeRef = ref<{ getWardrobeData: Function }>()
const otherRef = ref<{ getOtherData: Function }>()
const selectRoomList = ref<string[]>([])
const selectRoomTypeList = ref<string[]>([])
const roomChange = (event: string[]) => {
  selectRoomList.value = event
}
const getWriteData = async () => {
  const submitParams = {
    calculate_id: pageQuery.calculate_id,
    house_number: pageQuery.house_number,
    floor_info: [] as any[],
    house_info: [] as any[],
    carpentry_info: [] as any[],
    wardrobe_info: [] as any[],
    other_info: [],
  }
  let colData = [] as { name: string; value: string }[]
  tileRef.value!.colData.forEach((item) => {
    colData.push({
      name: item.name,
      value: item.value,
    })
  })
  submitParams.floor_info = colData
  if (typeof mineRoomRef.value?.getRoomData === 'function') {
    mineRoomRef.value?.getRoomData().forEach((item) => {
      submitParams.house_info.push(item)
    })
  } else {
    submitParams.house_info = []
  }
  ceilingRef.value?.getceilingData().forEach((item) => {
    submitParams.carpentry_info.push(item)
  })
  const wardrobeData = await wardrobeRef.value?.getWardrobeData()
  if (wardrobeData) {
    for (const item of wardrobeData) {
      item.forEach((wardrobeItem) => {
        submitParams.wardrobe_info.push(wardrobeItem)
      })
    }
  }
  submitParams.other_info = otherRef.value?.getOtherData()
  await saveGatherData(submitParams)
}
const handleSubmit = async () => {
  await getWriteData()
  await submitGather({
    calculate_id: pageQuery.calculate_id,
  })
  await getCalculateDetail({
    calculate_id: pageQuery.calculate_id,
    house_number: pageQuery.house_number,
  })
  if (pageQuery.type == '单') {
    window.api.refreshInitData()
  }
}
const handleReset = async () => {
  ElMessageBox.alert('重新提交核算会覆盖掉部分数值，您是否继续重新提交核算？ ', '温馨提示', {
    showCancelButton: true,
    callback: async (action: Action) => {
      if (action == 'confirm') {
        await getWriteData()
        await reGather({
          calculate_id: pageQuery.calculate_id,
        })
        await getCalculateDetail({
          calculate_id: pageQuery.calculate_id,
          house_number: pageQuery.house_number,
        })
        if (pageQuery.type == '单') {
          window.api.refreshInitData()
        }
      }
    },
  })
}
const { saveGatherData } = useCompute()
const { getCarpentryGather, submitGather, calculateInfo, getCalculateDetail, reGather } = useComputeForm()
const initForm = async () => {
  await getCalculateDetail({
    calculate_id: pageQuery.calculate_id,
    house_number: pageQuery.house_number,
  })
  const res = await getCarpentryGather({
    calculate_id: pageQuery.calculate_id,
    house_number: pageQuery.house_number,
  })

  if (res.length) {
    res.map((projectItem) => {
      if (projectItem.cate_name == '吊顶项目') {
        projectItem.carpentry_info.forEach((item) => {
          selectRoomTypeList.value.push(item.name)
        })
      }
    })
  }
}
await initForm()
const startCompute = () => {
  let house_info: RoomListModel[] = []
  if (typeof mineRoomRef.value?.getRoomData === 'function') {
    mineRoomRef.value?.getRoomData().forEach((item) => {
      house_info.push(item)
    })
    ceilingRef.value?.getComputeHouseInfo(house_info)
  } else {
    house_info = []
  }
}
</script>

<template>
  <main class="bg-white flex flex-col gap-3" style="height: -webkit-fill-available">
    <div class="px-6 h-[50px] border-b flex items-center bg-white border-l" style="width: -webkit-fill-available">
      <div class="flex gap-3" v-if="calculateInfo">
        <formButton @click="getWriteData">暂存数据</formButton>
        <formButton
          v-if="calculateInfo.template == 1 && calculateInfo.check_gather != 1 && pageQuery.type == '单'"
          @click="handleSubmit">
          保存模版
        </formButton>
        <formButton
          v-if="calculateInfo.check_gather != 1 && calculateInfo.template == 2 && pageQuery.isSave == '1' && pageQuery.type == '单'"
          @click="handleSubmit">
          提交数据
        </formButton>
        <formButton
          v-if="calculateInfo.check_gather == 1 && calculateInfo.check_lock != 1 && pageQuery.isSave == '1' && pageQuery.type == '单'"
          @click="handleReset">
          提交计算
        </formButton>
      </div>
    </div>
    <div class="px-6 pb-10 overflow-y-auto flex-1">
      <div class="text-base text-[#ff9600] text-center">说明：点击“采集项目名称”会提示相关采集项目说明。</div>
      <div id="tileRef"></div>
      <addTile ref="tileRef" />
      <div id="roomRef"></div>
      <addRoom @roomChange="roomChange" ref="mineRoomRef" />
      <div id="ceilingRef"></div>
      <addCeiling :selectRoomList="selectRoomTypeList" ref="ceilingRef" @startCompute="startCompute" />
      <div id="wardrobeRef"></div>
      <addWardrobe :selectRoomList="selectRoomList" ref="wardrobeRef" />
      <div id="otherRef"></div>
      <addOther ref="otherRef" :selectRoomList="selectRoomList" />
    </div>
  </main>
</template>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
.save-button {
  @apply text-white px-16 py-3 rounded-md cursor-pointer;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
</style>
